package com.example.wacoffee_manage.Service.Impl;

import com.example.wacoffee_manage.Mapper.GoodMapper;
import com.example.wacoffee_manage.Service.goodService;
import com.example.wacoffee_manage.common.PageResult;
import com.example.wacoffee_manage.pojo.Good;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class goodServiceImpl implements goodService {
   @Autowired
   private GoodMapper goodMapper;

    @Override
    public com.example.wacoffee_manage.common.PageResult getAllGoods(Good good) {
        PageHelper.startPage(good.getPage(),good.getPageSize());
        List<Good> goods= goodMapper.getAllGood(good);
        Page<Good> page=(Page<Good>) goods;
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Good good) {
        goodMapper.add(good);
        if(goodMapper.supplyIsFirstAppear(good.getSupplyName())==0){
         goodMapper.addSupply(good.getSupplyName());
         int goodId=goodMapper.getId(good.getName());
         int supplyId=goodMapper.getSupplyId(good.getSupplyName());
         goodMapper.addGoodSupply(goodId,supplyId);

        }
        else {
            int goodId=goodMapper.getId(good.getName());
            int supplyId=goodMapper.getSupplyId(good.getSupplyName());
            goodMapper.addGoodSupply(goodId,supplyId);

        }
    }

    @Override
    public Good getById(int id) {
        return goodMapper.getById(id);
    }

    @Override
    public void update(Good good) {
        goodMapper.update(good);
        if(goodMapper.supplyIsFirstAppear(good.getSupplyName())==0){
            goodMapper.addSupply(good.getSupplyName());
            int goodId=goodMapper.getId(good.getName());
            int supplyId=goodMapper.getSupplyId(good.getSupplyName());
            goodMapper.addGoodSupply(goodId,supplyId);
        }
        else {
            int goodId=goodMapper.getId(good.getName());
            int supplyId=goodMapper.getSupplyId(good.getSupplyName());
            goodMapper.addGoodSupply(goodId,supplyId);
        }
    }

    @Override
    public void delete(int id) {
        goodMapper.delete(id);
        goodMapper.deleteGoodToSupply(id);
    }

    @Override
    public List<Good> getAllGood() {
        return goodMapper.getAll();
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        goodMapper.deleteBatch(ids);

    }


}